<!--
*@Author: zt
*@Description: 角色管理
*@Date: 2024-08-14
-->
<template>
  <a-layout class="f-h-100 s-bg-white u-role-manager-box">
    <u-table-header>
      <a-form
        :model="searchF"
        :inline="true"
        class="f-search-tool-240"
        style="--width: 220px"
        label-width="80px"
        layout="horizontal"
      >
        <a-form-item label="角色模块类型">
          <u-select
            v-model:value="searchF.model.rolestype"
            :options="roleTypes"
            :fieldNames="{ label: 'name', value: 'id' }"
            allowClear
          />
        </a-form-item>
        <a-form-item label="角色名称">
          <u-input
            v-model:value="searchF.model.rolename"
            placeholder="角色名称"
            @enter="getSearch(1)"
          />
        </a-form-item>
        <a-form-item style="width: 700px">
          <a-space>
            <u-icon-button itype="search" @click="getSearch(1)">
              查询
            </u-icon-button>
            <u-icon-button itype="add" @click="toEdit(1)">新增</u-icon-button>
            <u-icon-button itype="edit" @click="toEdit(2)">编辑</u-icon-button>
            <u-icon-button itype="delete" type="button" @click="deleteBtn()">
              删除
            </u-icon-button>
          </a-space>
        </a-form-item>
      </a-form>
    </u-table-header>
    <u-table-content style="position: relative; padding: 0 12px">
      <u-table
        :columns="columns"
        :data="tabData"
        :loading="tabLoading"
        v-model:pagination="pagenation"
        @onDblclick="rowDblClick"
        :scroll="{ y: useTableScroll() }"
        @onSelect="({ selectedRows }) => (tabSelData = selectedRows)"
        @change="getSearch"
      />
    </u-table-content>

    <!-- 编辑弹窗 -->
    <Edit
      v-model:open="showEdit"
      :title="dialogTitle"
      width="45%"
      top="2vh"
      :keyid="updateKey"
      @close="showEdit = false"
      @success="getSearch(), (showEdit = false)"
    />
  </a-layout>
</template>
<script lang="ts" setup>
import { formtTreeData, formtTableEnum, formtTableEcho } from '@/util/format.ts'
import { isSel } from '@/common/model/base';
import { h, onMounted, reactive, ref } from 'vue';
import { nullC, numberC, alertC, confirmC } from '@/util/common';
import { storeToRefs } from 'pinia';
import { useBaseStore } from '@/store';
import { Button, Popconfirm, Space } from 'ant-design-vue';
import { useTableScroll } from '@/hooks/useTable';
import Edit from './Edit.vue';
import * as roleService from '@/service/system/role/index';
import * as enmuService from '@/service/enum/index';

const { ROLE_TYPE } = storeToRefs(useBaseStore());

let pagenation = reactive({
  total: 0,
  current: 1,
  pageSize: 50,
});

const searchF = reactive({
  model: {
    rolestype: null,
    rolename: '',
  },
  current: 1,
  size: 20,
  order: 'descending',
  sort: 'rolecode',
});
const roleTypes = ref([]);
const total = ref(0);
const tabLoading = ref(false);
const tabData = ref([]);
const tabSelData = ref([]);
let columns = ref([
  {
    title: '序号',
    width: 50,
    align: 'center',
    dataIndex: 'index',
    customRender: ({ index }) => (index += 1),
  },
  {
    title: '角色模块类型',
    width: 150,
    align: 'center',
    dataIndex: 'rolestype_echo',
    sortable: 'custom',
  },
  {
    title: '角色代码',
    width: 150,
    align: 'center',
    dataIndex: 'rolecode',
    sortable: 'custom',
  },
  {
    title: '角色名称',
    width: 200,
    align: 'center',
    dataIndex: 'rolename',
    sortable: 'custom',
  },
  { title: '是否使用', width: 120, align: 'center', dataIndex: 'isuse_echo' },
  {
    title: '是否系统级别',
    width: 120,
    align: 'center',
    dataIndex: 'issystem_echo',
  },
  { title: '备注', width: 150, align: 'center', dataIndex: 'remark' },
  {
    title: '编辑',
    width: 80,
    dataIndex: 'edit1',
    icon: 'edit',
    align: 'center',
    customRender: ({ record, text, index }) => {
      return h(Space, () => [
        h(
          Popconfirm,
          {
            title: '您确定要删除吗？',
            onConfirm: () => deleteBtn(record),
          },
          () => [h(Button, { type: 'link' }, () => '删除')]
        ),
      ]);
    },
  },
]);

const dialogTitle = ref('新增人员');
const showEdit = ref(false);
const updateKey = ref('');

onMounted(async () => {
  await getEnum();
  getSearch(1);
});

// 列表分页查询
const getSearch = (current?: number) => {
  if (current == 1) {
    searchF.current = current;
    pagenation.current = current;
  }

  let tform = JSON.parse(JSON.stringify(searchF));
  tform.model.rolename = nullC(tform.model.rolename, null);
  tform.model.rolestype = nullC(tform.model.rolestype, null);

  tform.size = pagenation.pageSize;
  tform.current = pagenation.current;

  tabLoading.value = true;
  roleService
    .rolePage(tform)
    .then(res => {
      tabLoading.value = false;
      if (res.code == 0) {
        total.value = numberC(res.data.total);

        let tdata = formtTableEcho(res.data.records);
        tdata = formtTableEnum(roleTypes.value, tdata, 'rolestype');
        tdata = formtTableEnum(isSel(), tdata, 'isuse');
        tdata = formtTableEnum(isSel(), tdata, 'issystem');
        tdata.forEach(
          item => (item.edit = "<i class='iconfont icon-bianji f-cursor'></i>")
        );

        tabData.value.splice(0, tabData.value.length, ...tdata);
      }
    })
    .catch(() => {
      tabLoading.value = false;
    });
};

// 获取枚举下拉数据
const getEnum = () => {
  return roleTypes.value.splice(0, roleTypes.value.length, ...ROLE_TYPE.value);
};

// type 1 新增、type 2 修改按钮
const toEdit = type => {
  if (type == 1) {
    dialogTitle.value = '角色新增';
    updateKey.value = '';
  }
  // 修改
  else if (type == 2) {
    if (tabSelData.value.length != 1) {
      alertC('只能选择一条数据进行编辑！');
      return;
    }

    updateKey.value = tabSelData.value[0]['keyid'];
    dialogTitle.value = '角色编辑';
  }
  showEdit.value = true;
};

// 行双击
const rowDblClick = data => {
  showEdit.value = true;
  updateKey.value = data['keyid'];
  dialogTitle.value = '角色编辑';
};

// 删除功能
const deleteBtn = (record?: any) => {
  let arrs = record ? [record] : tabSelData.value;

  if (arrs.length == 0) {
    alertC('请先选择要删除的数据！');
    return;
  }

  let ids = arrs.map(item => item.keyid);
  tabLoading.value = true;
  roleService
    .del({ ids: ids.join(',') })
    .then(res => {
      tabLoading.value = false;
      if (res.code == 0) {
        getSearch(1);
        updateKey.value = '';
        alertC(res.msg, 'success');
      } else {
        alertC(res.msg, 'warning');
      }
    })
    .catch(err => {
      tabLoading.value = false;
    });
};
</script>
<style lang="scss">
.u-jhk-serch-datepicker {
  .el-range-separator {
    padding: 0;
    width: unset;
  }
}

.u-role-manager-box {
  .ant-form-item {
    margin-bottom: 10px !important;
  }
}
</style>
